#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import sys
import os
from collections import defaultdict

def count_letter_frequency(filename: str) -> None:
    """
    统计文件中字母频率并输出结果
    """
    try:
        # 初始化字母计数器
        letter_count = defaultdict(int)
        total_letters = 0
        
        # 读取文件并统计
        with open(filename, 'r', encoding='utf-8') as file:
            for line in file:
                for char in line:
                    if char.isalpha():  # 只统计字母
                        lowercase_char = char.lower()
                        letter_count[lowercase_char] += 1
                        total_letters += 1
        
        # 处理空文件情况
        if total_letters == 0:
            print("No letters found in the file")
            return
        
        # 计算频率并排序
        results = []
        for letter, count in letter_count.items():
            percentage = (count / total_letters) * 100
            results.append((letter, count, percentage))
        
        # 排序：频率降序，频率相同按字母升序
        results.sort(key=lambda x: (-x[1], x[0]))
        
        # 输出结果（使用英文避免乱码）
        print(f"{'Letter':<6} {'Count':<8} {'Percentage':<10}")
        print("-" * 25)
        for letter, count, percentage in results:
            print(f"{letter:<6} {count:<8} {percentage:.2f}%")
            
        print(f"\nTotal letters: {total_letters}")
        
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
        sys.exit(1)
    except Exception as e:
        print(f"Error: Exception occurred while reading file - {e}")
        sys.exit(1)

def main():
    """
    主函数：处理命令行参数
    """
    parser = argparse.ArgumentParser(description='Count letter frequency in English text')
    parser.add_argument('-c', '--count', required=True, 
                       help='Filename to analyze')
    
    args = parser.parse_args()
    
    # 检查文件是否存在
    if not os.path.exists(args.count):
        print(f"Error: File '{args.count}' does not exist")
        sys.exit(1)
    
    count_letter_frequency(args.count)

if __name__ == "__main__":
    main()
